package com.mida.app.report.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mida.app.report.service.MasterDataSvc;
import com.mida.app.report.service.RequestFormBmsSvc;
import com.mida.app.report.service.RequestFormService;
import com.mida.app.report.service.RequestFormUtilSvc;
import com.mida.app.report.vo.request.*;
import com.mida.app.report.vo.request.reqeustform.RegistrationListRequest;
import com.mida.bms.customer.api.PersonOperationApi;
import com.mida.bms.customer.vo.person.PatientInfoVo;
import com.mida.bms.customer.vo.person.PersonInfoConditionVo;
import com.mida.bms.requestform.api.RequestFormApi;
import com.mida.bms.requestform.dto.ApntNursingRecordsSetDto;
import com.mida.bms.requestform.dto.RequestDiagnosisSetDto;
import com.mida.bms.requestform.dto.RequestPageInfoDto;
import com.mida.bms.requestform.dto.ServiceInstanceInfoDto;
import com.mida.bms.requestform.enums.ProcessStatusEnum;
import com.mida.bms.requestform.request.reqeustfrom.RequestServiceInstasnceRequest;
import com.mida.dms.mdm.api.provider.IServiceInstanceApi;
import com.mida.tool.common.ret.RespBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RequestFormServiceImpl implements RequestFormService {

    /**
     * 申请单域Api
     */
    @Autowired
    private RequestFormBmsSvc requestFormBmsSvc;

    /**
     * 主数据Api
     */
    @Autowired
    private MasterDataSvc masterDataSvc;

    @Autowired
    private RequestFormApi requestFormApi;

    @Autowired
    private PersonOperationApi personOperationApi;

    @Autowired
    private IServiceInstanceApi iServiceInstanceApi;

    @Autowired
    private RequestFormUtilSvc requestFormUtilSvcImpl;


    @Override
    public List<ReqeustServiceInstanceVo> getReqeustAllServiceInstances(List<String> requestSoids) {
        List<ReqeustServiceInstanceVo> res = new ArrayList<>();
        if (CollectionUtils.isEmpty(requestSoids)) {
            return res;
        }
        List<BigDecimal> collect = requestSoids.stream().map(BigDecimal::new).collect(Collectors.toList());
        //根据申请单soid批量获取相应的检查服务实例
        RespBody<Map<BigDecimal, List<ServiceInstanceInfoDto>>> requestSoidServiceInstanceMap = requestFormBmsSvc.getBigDecimalListMap(collect);
        if (ObjectUtil.isEmpty(requestSoidServiceInstanceMap)||CollectionUtils.isEmpty(requestSoidServiceInstanceMap.getData())) {
            return res;
        }
        Map<BigDecimal, List<ServiceInstanceInfoDto>> map = requestSoidServiceInstanceMap.getData();
        //注意区分索引
        List<HashSet<BigDecimal>> soidsSets = requestFormUtilSvcImpl.changeSoidsMapToSets(map);
        //索引0-msdServiceInstanceSoids
        Map<BigDecimal, String> serviceInstanceNameMap = requestFormUtilSvcImpl.changeServiceInstanceNameSetMap(soidsSets.get(0));
        //索引1-businessUnitSoids
        Map<BigDecimal, String> businessNameMap = requestFormUtilSvcImpl.changeBusinessNameSetToMap(soidsSets.get(1));
        for (List<ServiceInstanceInfoDto> value : map.values()) {
            //直接过滤出已检查状态的申请单，其他状态的申请单不返回
//            List<ServiceInstanceInfo> checkedRequestServiceInstances = value.stream().filter(a -> new BigDecimal(RequestStatusEnum.checked.getValue()).equals(a.getRequestStatus())).collect(Collectors.toList());
            //置检查服务实例属性soid对应中文信息
            List<ReqeustServiceInstanceVo> reqeustServiceInstanceVos = this.setReqeustServiceInstanceVos(value, serviceInstanceNameMap, businessNameMap);
            res.addAll(reqeustServiceInstanceVos);
        }
        return res;
    }

    @Override
    public Page<RegistrationListCompleteInfoVo> queryAllRequestFormPageInfo(RegistrationListRequest request) {
        try {
            //最终返回结果
            Page<RegistrationListCompleteInfoVo> res = new Page<>();
            RespBody<Page<RequestPageInfoDto>> result = getRequestFormPage(request);
            Page<RequestPageInfoDto> page = ObjectUtil.isNotEmpty(result) && ObjectUtil.isNotEmpty(result.getData()) ? result.getData() : new Page<>();
            if (ObjectUtils.isEmpty(page) || ObjectUtils.isEmpty(page.getRecords())) {
                return res;
            }
            //查询患者信息
            List<RequestPageInfoDto> requestPageInfos = page.getRecords();
            //分页返回体的原始索引，用来保证返回数据不会因为多线程错乱顺序
            List<String> recordsKey = requestPageInfos.stream().map(RequestPageInfoDto::getRequestSoid).collect(Collectors.toList());
            Map<String, RegistrationListCompleteInfoVo> records = new HashMap<>();
            //批量查询患者信息并封装成map
            Map<BigDecimal, PatientPageInfoVo> personDetailInfosMap = requestFormUtilSvcImpl.queryPatientInfoVosToMap(requestPageInfos);
            //批量查询检查服务实例信息并封装成map
            Map<BigDecimal, List<ServiceInstanceInfoDto>> serviceInstanceMap = requestFormUtilSvcImpl.changeServiceInstancesToMap(requestPageInfos);
            //获取需要批量查询的soid
            //注意区分索引
            List<HashSet<BigDecimal>> soidsSets = requestFormUtilSvcImpl.changeSoidsMapToSets(serviceInstanceMap);
            //索引0-msdServiceInstanceSoids
            Map<BigDecimal, String> serviceInstanceNameMap = requestFormUtilSvcImpl.changeServiceInstanceNameSetMap(soidsSets.get(0));
            //索引1-businessUnitSoids
            Map<BigDecimal, String> businessNameMap = requestFormUtilSvcImpl.changeBusinessNameSetToMap(soidsSets.get(1));
            //索引2-dataSetSoids
            Map<BigDecimal, String> dataSetSoidNameMap = requestFormUtilSvcImpl.changeDataSetSoidNameSetToMap(soidsSets.get(2));
            //索引3-requestDoctorSoids
            Map<BigDecimal, String> requestDoctorSoidNameMap = requestFormUtilSvcImpl.changeRequestDoctorSoidNameSetToMap(soidsSets.get(3));

            //分页数据封装填充
            requestFormUtilSvcImpl.extracted(requestPageInfos, records, personDetailInfosMap, serviceInstanceMap,
                    serviceInstanceNameMap, businessNameMap, dataSetSoidNameMap, requestDoctorSoidNameMap);
            BeanUtil.copyProperties(page, res);
            List<RegistrationListCompleteInfoVo> recordAll = new ArrayList<>();
            for (String mapKey : recordsKey) {
                recordAll.add(records.get(mapKey));
            }
            res.setRecords(recordAll);
            return res;
        } catch (Exception e) {
            log.info("RequestFormServiceImpl.queryAllRequestFormPageInfo 报告分页查询申请单出错:{}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取申请单分页数据
     * @param request
     * @return
     */
    @Override
    public RespBody<Page<RequestPageInfoDto>> getRequestFormPage(RegistrationListRequest request) {
        //转换请求体
        com.mida.bms.requestform.request.reqeustfrom.RegistrationListRequest registrationListRequest =
                BeanUtil.copyProperties(request, com.mida.bms.requestform.request.reqeustfrom.RegistrationListRequest.class);
        /*
         * todo
         * @Author guoqiubo
         * @Date 2021年6月2日 23:39:53
         * @Description 如果检查号入参不为空，先去登记服务查询该检查号对应的所有申请单号，作为查询条件
         */
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(request.getExaminationVisitSoid())) {
//                todo 上机中台接口
            Map<BigDecimal, List<BigDecimal>> registrationNoWithExamNo = new HashMap<>();
            Map<BigDecimal, List<BigDecimal>> requestSoidMapExamNo = new HashMap<>();
//                Map<BigDecimal, List<BigDecimal>> registrationNoWithExamNo = examBmsApi.getRegistrationNoWithExamNo(Arrays.asList(request.getExaminationVisitSoid()));
            List<BigDecimal> registrationFromSoids = ObjectUtil.isEmpty(registrationNoWithExamNo) ? new ArrayList<>() : registrationNoWithExamNo.get(new BigDecimal(request.getExaminationVisitSoid()));
            List<BigDecimal> requestSoidsFromExamNo = CollectionUtils.isEmpty(registrationFromSoids) && ObjectUtils.isNotEmpty(requestSoidMapExamNo) ? new ArrayList<>() : requestSoidMapExamNo.get(new BigDecimal(request.getExaminationVisitSoid()));
//                        BigDecimal requestSoid = reserveBmsApi.queryRequestByRegistrationForm(fromSoid);
            registrationListRequest.setRequestSoidsOfExaminationVisitSoid(requestSoidsFromExamNo.stream().filter(ObjectUtils::isNotEmpty).map(BigDecimal::toPlainString).collect(Collectors.toList()));
        }
        //前台设置领域标识为报告
        registrationListRequest.setProcessStatus(ProcessStatusEnum.REPORT.getValue());
        //关闭预约标识
        registrationListRequest.setIsBooking(false);
        //根据姓名查询申请单
        if (ObjectUtil.isNotEmpty(request.getPersonName())) {
            PersonInfoConditionVo conditionVo = new PersonInfoConditionVo();
            conditionVo.setPersonName(request.getPersonName());
            RespBody<List<PatientInfoVo>> personInfos = personOperationApi.getPersonInfos(conditionVo);
            List<String> customerSiods = ObjectUtil.isEmpty(personInfos) ? null : personInfos.getData().stream().filter(ObjectUtil::isNotEmpty).filter(a -> ObjectUtil.isNotEmpty(a.getCustomerSoId())).map(PatientInfoVo::getCustomerSoId).collect(Collectors.toList()).get(0);
            registrationListRequest.setCustomerSoids(CollectionUtils.isEmpty(customerSiods) ? null : customerSiods);
        }
        RespBody<Page<RequestPageInfoDto>> result = requestFormBmsSvc.getRequestPageInfoWithCondition(registrationListRequest);
        return result;
    }

    @Override
    public List<ReqeustServiceInstanceVo> getReqeustServiceInstanceVos
            (List<RequestServiceInstasnceRequest> requests) {
        if (CollectionUtils.isEmpty(requests)) {
            return null;
        }
        List<ServiceInstanceInfoDto> instanceVos = requestFormBmsSvc.getReqeustServiceInstanceVos(requests);
        if (null == instanceVos) {
            return null;
        }
        Map<BigDecimal, List<ServiceInstanceInfoDto>> ServiceInstanceInfoDtoMap = instanceVos.stream().filter(ObjectUtil::isNotEmpty).filter(a -> ObjectUtil.isNotEmpty(a.getRequestSoid())).collect(Collectors.groupingBy(ServiceInstanceInfoDto::getRequestSoid));
        //注意区分索引
        List<HashSet<BigDecimal>> soidsSets = requestFormUtilSvcImpl.changeSoidsMapToSets(ServiceInstanceInfoDtoMap);
        //索引0-msdServiceInstanceSoids
        Map<BigDecimal, String> serviceInstanceNameMap = requestFormUtilSvcImpl.changeServiceInstanceNameSetMap(soidsSets.get(0));
        //索引1-businessUnitSoids
        Map<BigDecimal, String> businessNameMap = requestFormUtilSvcImpl.changeBusinessNameSetToMap(soidsSets.get(1));

        //置检查服务实例属性soid对应中文信息
        List<ReqeustServiceInstanceVo> reqeustServiceInstanceVos = setReqeustServiceInstanceVos(instanceVos, serviceInstanceNameMap, businessNameMap);
        List<String> requestSoids = reqeustServiceInstanceVos.stream().map(ReqeustServiceInstanceVo::getRequestSoid).collect(Collectors.toList());
        RespBody<List<RequestDiagnosisSetDto>> requestDiagnosisSetDtos = requestFormBmsSvc.getRequestDiagnosisWithRequestSoids(requestSoids);
        List<RequestDiagnosisSetVo> requestDiagnosisSetVos = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(requestDiagnosisSetDtos) && ObjectUtils.isNotEmpty(requestDiagnosisSetDtos.getData())) {
            List<RequestDiagnosisSetDto> data = requestDiagnosisSetDtos.getData();
            requestDiagnosisSetVos = BeanUtil.copyToList(data, RequestDiagnosisSetVo.class);
        }
        Map<BigDecimal, List<RequestDiagnosisSetVo>> map = requestDiagnosisSetVos.stream().collect(Collectors.groupingBy(RequestDiagnosisSetVo::getRequestSoid));
        reqeustServiceInstanceVos.forEach(a -> {
            List<RequestDiagnosisSetVo> requestDiagnosisSetVos1 = map.get(new BigDecimal(a.getRequestSoid()));
            a.setRequestDiagnosisSetVos(requestDiagnosisSetVos1);
        });
        //根据申请单标识对检查服务实例进行分组
        return reqeustServiceInstanceVos;
    }


    /**
     * 设置检查服务实例属性soid对应中文信息
     * @param serviceInstances
     * @param serviceInstancesMap
     * @param businessNameMap
     * @return
     */
    @Deprecated
    private List<ReqeustServiceInstanceVo> setReqeustServiceInstanceVos(List<ServiceInstanceInfoDto> serviceInstances,
                                                                        Map<BigDecimal, String> serviceInstancesMap,
                                                                        Map<BigDecimal, String> businessNameMap) {
        Map<BigDecimal, List<ServiceInstanceInfoDto>> collect = serviceInstances.stream().collect(Collectors.groupingBy(ServiceInstanceInfoDto::getRequestSoid));
        Set<BigDecimal> requestSoids = collect.keySet();
        List<ReqeustServiceInstanceVo> res = new ArrayList<>();
        for (BigDecimal requestSoid : requestSoids) {
            HashSet<String> requestMethodsSet = new HashSet<>();
            HashSet<String> requestPartsSet = new HashSet<>();
            HashSet<String> requestExamTypesSet = new HashSet<>();
            HashSet<String> requestOrientationNamesSet = new HashSet<>();
            HashSet<String> requestExamTechNamesSet = new HashSet<>();
            List<ServiceInstanceVo> serviceInstanceVos = new ArrayList<>();
            List<ServiceInstanceInfoDto> serviceInstanceInfos = collect.get(requestSoid);
            if (CollectionUtils.isEmpty(serviceInstanceInfos)) {
                continue;
            }
            /**
             * 将申请单下所有检查服务实例根据检查服务实例soid进行分组
             */
            Map<BigDecimal, List<ServiceInstanceInfoDto>> ServiceInstanceInfoMap = serviceInstanceInfos.stream().collect(Collectors.groupingBy(ServiceInstanceInfoDto::getMsdServiceInstanceSoid));
            ReqeustServiceInstanceVo reqeustServiceInstanceVo = new ReqeustServiceInstanceVo();
            ServiceInstanceInfoDto instanceInfo = serviceInstanceInfos.get(0);
            if (ObjectUtils.isNotEmpty(instanceInfo)) {
                reqeustServiceInstanceVo.setRequestSoid(ObjectUtils.isEmpty(instanceInfo.getRequestSoid()) ? null : instanceInfo.getRequestSoid().toPlainString());
                reqeustServiceInstanceVo.setEmergencySign(ObjectUtils.isEmpty(instanceInfo.getEmergencySign()) ? null : instanceInfo.getEmergencySign().toPlainString());
                reqeustServiceInstanceVo.setClinicalPurpose(instanceInfo.getClinicalPurpose());
                reqeustServiceInstanceVo.setPreliminaryDiagnosis(instanceInfo.getPreliminaryDiagnosis());
                reqeustServiceInstanceVo.setClinicalSummary(instanceInfo.getClinicalSummary());
                reqeustServiceInstanceVo.setRequestStatus(ObjectUtils.isEmpty(instanceInfo.getRequestStatus()) ? null : instanceInfo.getRequestStatus().toPlainString());
                reqeustServiceInstanceVo.setNursingWardSoid(ObjectUtils.isEmpty(instanceInfo.getNursingWardSoid()) ? null : instanceInfo.getNursingWardSoid().toPlainString());
                reqeustServiceInstanceVo.setManualSign(ObjectUtils.isEmpty(instanceInfo.getManualSign()) ? null : instanceInfo.getManualSign().toPlainString());
                reqeustServiceInstanceVo.setBedNo(ObjectUtils.isEmpty(instanceInfo.getBedNo()) ? null : instanceInfo.getBedNo().toPlainString());
                reqeustServiceInstanceVo.setVisitScenceCode(ObjectUtils.isEmpty(instanceInfo.getVisitScenceCode()) ? null : instanceInfo.getVisitScenceCode().toPlainString());
                reqeustServiceInstanceVo.setPatientVisitSoid(ObjectUtils.isEmpty(instanceInfo.getPatientVisitSoid()) ? null : instanceInfo.getPatientVisitSoid());
                reqeustServiceInstanceVo.setRequestDept(ObjectUtils.isEmpty(instanceInfo.getRequestDept()) ? null : instanceInfo.getRequestDept().toPlainString());
                reqeustServiceInstanceVo.setRequestDoctor(ObjectUtils.isEmpty(instanceInfo.getRequestDoctor()) ? null : instanceInfo.getRequestDoctor().toPlainString());
                reqeustServiceInstanceVo.setPatientId(ObjectUtils.isEmpty(instanceInfo.getPatientSoid()) ? null : instanceInfo.getPatientSoid().toPlainString());

                //检查技术参数描述
                reqeustServiceInstanceVo.setMedicalDeviceExampleDesc(
                        ObjectUtils.isEmpty(instanceInfo.getInspectionTechnicalParamDesc()) ? null :
                                instanceInfo.getInspectionTechnicalParamDesc());
                //检查技术参数SoId
                reqeustServiceInstanceVo.setMedicalDeviceExampleSoId(
                        ObjectUtils.isEmpty(instanceInfo.getExamtechSoid()) ? null :
                                instanceInfo.getExamtechSoid().toPlainString());
                //检查技术主档SoId
                reqeustServiceInstanceVo.setRequestExamTechSoId(
                        ObjectUtils.isEmpty(instanceInfo.getRequestExamTech()) ? null :
                                instanceInfo.getRequestExamTech().toPlainString());

            }
            /**
             * 将申请单下所有检查服务实例进行遍历
             */
            Set<BigDecimal> msdServiceInstanceSoids = ServiceInstanceInfoMap.keySet();
            for (BigDecimal msdServiceInstanceSoid : msdServiceInstanceSoids) {
                ServiceInstanceVo serviceInstanceVo = ServiceInstanceVo.builder().build();
                /**
                 * 单个检查服务实例
                 * 处理一个检查服务实例对应多个部位的情况
                 */
                List<ServiceInstanceInfoDto> serviceInstanceInfo = ServiceInstanceInfoMap.get(msdServiceInstanceSoid);

                List<SoidMapNameVo> examTypes = new ArrayList<>();
                List<SoidMapNameVo> orientations = new ArrayList<>();
                List<SoidMapNameVo> parts = new ArrayList<>();
                List<SoidMapNameVo> methods = new ArrayList<>();
                List<SoidMapNameVo> examTechs = new ArrayList<>();
                HashSet<String> methodsSet = new HashSet<>();
                HashSet<String> partsSet = new HashSet<>();
                HashSet<String> examTypesSet = new HashSet<>();
                HashSet<String> orientationNamesSet = new HashSet<>();
                HashSet<String> examTechNamesSet = new HashSet<>();
                for (ServiceInstanceInfoDto info : serviceInstanceInfo) {
                    //从主数据获取检查服务实例信息 todo 数据来源换成iris存储的检查服务实例信息
                    String checkUnitName = ObjectUtils.isNotEmpty(info.getExecuteDept()) && ObjectUtils.isNotEmpty(businessNameMap) ? businessNameMap.get(info.getExecuteDept()) : null;
                    String instanceName = ObjectUtils.isNotEmpty(info.getMsdServiceInstanceSoid()) && ObjectUtils.isNotEmpty(serviceInstancesMap) ? serviceInstancesMap.get(info.getMsdServiceInstanceSoid()) : null;
                    serviceInstanceVo.setCheckUnitName(checkUnitName);
                    serviceInstanceVo.setServiceDefineSoid(info.getServiceDefineSoid());
                    serviceInstanceVo.setServiceInstanceName(instanceName);
                    serviceInstanceVo.setMsdServiceInstanceSoid(ObjectUtils.isEmpty(info.getMsdServiceInstanceSoid()) ? null : info.getMsdServiceInstanceSoid().toPlainString());
                    serviceInstanceVo.setRequestServiceSoid(ObjectUtils.isEmpty(info.getRequestServiceSoid()) ? null : info.getRequestServiceSoid().toPlainString());
                    String part = requestFormUtilSvcImpl.setSoidMapName(parts, info.getExamParts());
                    String method = requestFormUtilSvcImpl.setSoidMapName(methods, info.getExamMethod());
                    String examType = requestFormUtilSvcImpl.setSoidMapName(examTypes, info.getExamType());
                    String orientation = requestFormUtilSvcImpl.setSoidMapName(orientations, info.getOrientationSoid());
                    String examTechName = requestFormUtilSvcImpl.setSoidMapName(examTechs, info.getExamtechSoid());
                    requestFormUtilSvcImpl.addStringToSet(part, requestPartsSet, partsSet);
                    requestFormUtilSvcImpl.addStringToSet(method, requestMethodsSet, methodsSet);
                    requestFormUtilSvcImpl.addStringToSet(examType, requestExamTypesSet, examTypesSet);
                    requestFormUtilSvcImpl.addStringToSet(orientation, requestOrientationNamesSet, orientationNamesSet);
                    requestFormUtilSvcImpl.addStringToSet(examTechName, requestExamTechNamesSet, examTechNamesSet);
                }
                String methodNames = requestFormUtilSvcImpl.apendNameStringFromSet(methodsSet);
                String partNames = requestFormUtilSvcImpl.apendNameStringFromSet(partsSet);
                String examTypeNames = requestFormUtilSvcImpl.apendNameStringFromSet(examTypesSet);
                String orientationNames = requestFormUtilSvcImpl.apendNameStringFromSet(orientationNamesSet);
                String examTechNames = requestFormUtilSvcImpl.apendNameStringFromSet(examTechNamesSet);

                serviceInstanceVo.setExamServiceType(examTypes);
                serviceInstanceVo.setExamServiceTypeName(examTypeNames);
                serviceInstanceVo.setMethodNames(methodNames);
                serviceInstanceVo.setMethods(methods);
                serviceInstanceVo.setExamtech(examTechs);
                serviceInstanceVo.setExamtechName(examTechNames);
                serviceInstanceVo.setPartNames(partNames);
                serviceInstanceVo.setParts(parts);
                serviceInstanceVo.setOrientationNames(orientationNames);
                serviceInstanceVo.setOrientations(orientations);
                serviceInstanceVos.add(serviceInstanceVo);
            }

            String requestMethodNames = requestFormUtilSvcImpl.apendNameStringFromSet(requestMethodsSet);
            String requestPartNames = requestFormUtilSvcImpl.apendNameStringFromSet(requestPartsSet);
            String requestExamTypeNames = requestFormUtilSvcImpl.apendNameStringFromSet(requestExamTypesSet);
            String requestOrientationNames = requestFormUtilSvcImpl.apendNameStringFromSet(requestOrientationNamesSet);
            String requestExamTechNames = requestFormUtilSvcImpl.apendNameStringFromSet(requestExamTechNamesSet);

            reqeustServiceInstanceVo.setServiceInstanceVos(serviceInstanceVos);
            reqeustServiceInstanceVo.setExamServiceTypeName(requestExamTypeNames);
            reqeustServiceInstanceVo.setMethodNames(requestMethodNames);
            reqeustServiceInstanceVo.setPartNames(requestPartNames);
            reqeustServiceInstanceVo.setOrientationNames(requestOrientationNames);
            reqeustServiceInstanceVo.setExamTechNames(requestExamTechNames);
            res.add(reqeustServiceInstanceVo);
        }
        return res;
    }

    @Override
    public List<RequestAndPatientInfoVo> findPatientMedicalByRequestSoids
            (List<RequestPsersonsoidRequest> requests) throws NoSuchFieldException {
        if (CollectionUtils.isEmpty(requests)) {
            return null;
        }
        List<String> personsoids = requests.stream().map(RequestPsersonsoidRequest::getPersonSoid).collect(Collectors.toList());
        List<String> requestSoids = requests.stream().map(RequestPsersonsoidRequest::getRequestSoid).collect(Collectors.toList());
        List<ReqeustServiceInstanceVo> reqeustAllServiceInstances = getReqeustAllServiceInstances(requestSoids);
        Set<BigDecimal> requestDepts = reqeustAllServiceInstances.stream().filter(a -> ObjectUtil.isNotEmpty(a.getRequestDept())).map(a -> new BigDecimal(a.getRequestDept())).collect(Collectors.toSet());
        Set<BigDecimal> requestDoctors = reqeustAllServiceInstances.stream().filter(a -> ObjectUtil.isNotEmpty(a.getRequestDoctor())).map(a -> new BigDecimal(a.getRequestDoctor())).collect(Collectors.toSet());
        Map<BigDecimal, String> businessNameMap = requestFormUtilSvcImpl.changeBusinessNameSetToMap(requestDepts);
        Map<BigDecimal, String> requestDoctorNameMap = requestFormUtilSvcImpl.changeRequestDoctorSoidNameSetToMap(requestDoctors);
        Map<String, PatientPageInfoVo> patientPageInfoVoMap = queryPersonInfosByPersonSoids(personsoids);
        Map<String, ReqeustServiceInstanceVo> serviceInstanceVoMap = reqeustAllServiceInstances.stream().collect(Collectors.toMap(ReqeustServiceInstanceVo::getRequestSoid, a -> a));
        List<RequestAndPatientInfoVo> res = requests.stream()
                .map(a -> RequestAndPatientInfoVo.builder()
                        .patientPageInfoVo(ObjectUtils.isEmpty(a.getPersonSoid()) ? null : patientPageInfoVoMap.get(a.getPersonSoid()))
                        .reqeustServiceInstanceVo(ObjectUtils.isEmpty(a.getRequestSoid()) ? null : serviceInstanceVoMap.get(a.getRequestSoid()))
                        .build()
                ).map(
                        a -> {
                            try {
//                                ReqeustServiceInstanceVo reqeustServiceInstanceVo = a.getReqeustServiceInstanceVo();
                                ReqeustServiceInstanceVo reqeustServiceInstanceVo = a.getReqeustServiceInstanceVo();
                                reqeustServiceInstanceVo.setRequestDept(businessNameMap.get(new BigDecimal(reqeustServiceInstanceVo.getRequestDept())));
                                reqeustServiceInstanceVo.setRequestDoctor(requestDoctorNameMap.get(new BigDecimal(reqeustServiceInstanceVo.getRequestDoctor())));
                            } catch (Exception e) {
                                log.info("RegistrationFormServiceImpl.findPatientMedicalByRequestSoids return RequestAndPatientInfoVo error msg={}", e.getMessage());
                            }
                            return a;
                        }
                ).collect(Collectors.toList());
        return res;
    }


    /**
     * 根据personSoids批量查询患者信息
     *
     * @param personSoids
     * @return
     * @throws NoSuchFieldException
     */
//    @Override
    public Map<String, PatientPageInfoVo> queryPersonInfosByPersonSoids(List<String> personSoids) throws
            NoSuchFieldException {
        if (CollectionUtils.isEmpty(personSoids)) {
            return null;
        }
        PersonInfoConditionVo personInfoConditionVo = new PersonInfoConditionVo();
        personInfoConditionVo.setPersonSoIds(personSoids);
        RespBody<List<PatientInfoVo>> personInfosResp = personOperationApi.getPersonInfos(personInfoConditionVo);
        List<PatientInfoVo> personInfosRespData = personInfosResp.getData();
        return personInfosRespData.stream().map(a -> setPatientPageInfoVo(a)).collect(Collectors.toMap(PatientPageInfoVo::getApntPersonSoid, a -> a,(key0,key1) -> key0));
    }

    /**
     * 填充身份证、地址等信息
     *
     * @param personDetailInfo
     * @return
     */
    private PatientPageInfoVo setPatientPageInfoVo(PatientInfoVo personDetailInfo) {
        List<String> stringList = new ArrayList<>();
        stringList.add(personDetailInfo.getPersonSoId());
        RespBody<List<ApntNursingRecordsSetDto>> byPersonSoids = requestFormApi.getNursingRecordsByPersonSoids(stringList);
        List<ApntNursingRecordsSetDto> soidsData = byPersonSoids.getData();
        PatientPageInfoVo patientPageInfoVo = PatientPageInfoVo.builder()
                .idCardNo(personDetailInfo.getIdCardNo())
                .address(personDetailInfo.getCustomerAddress())
                .apntPersonSoid(ObjectUtils.isEmpty(personDetailInfo.getPersonSoId()) ? null : personDetailInfo.getPersonSoId())
                .personName(personDetailInfo.getPersonName())
                .phoneNo(personDetailInfo.getContactNo())
//                .weight(soidsData.get(0).getWeight().toString())
                .weight(String.valueOf(soidsData.get(0).getWeight()))
                .customerSoid(personDetailInfo.getCustomerSoId().get(0))
                .build();
        //根据身份证设置个人信息
        setPersonInfoByIdCard(patientPageInfoVo);
        return patientPageInfoVo;
    }

    /**
     * 根据身份证设置个人信息
     *
     * @param patientPageInfoVo
     */
    private void setPersonInfoByIdCard(PatientPageInfoVo patientPageInfoVo) {
        if (StringUtils.isNotBlank(patientPageInfoVo.getIdCardNo())) {
            patientPageInfoVo.setAge(Integer.valueOf(IdcardUtil.getAgeByIdCard(patientPageInfoVo.getIdCardNo())).toString());
            String birthDate = Integer.valueOf(IdcardUtil.getBirthByIdCard(patientPageInfoVo.getIdCardNo())).toString();
            patientPageInfoVo.setBirthDate(birthDate.substring(0, 4) + "-" + birthDate.substring(4, 6) + "-" + birthDate.substring(6));
            patientPageInfoVo.setGenderName(1 == IdcardUtil.getGenderByIdCard(patientPageInfoVo.getIdCardNo()) ? "男" : "女");
            patientPageInfoVo.setGenderCode(1 == IdcardUtil.getGenderByIdCard(patientPageInfoVo.getIdCardNo()) ? "375" : "376");
        }
    }
}
